import React from "react";
import { Button,Card,Col,Select,Form,Radio,Input,notification,Row,DatePicker} from "antd";
import { loadTaskDetail, addTask,getManagerList,getWplList } from "@/services/TaskCenter";
import { getAllProject,loadProjectDetail } from "@/services/ProjectCenter";
import { getAllUser } from "@/services/UserCenter";
import { getAllSnList } from "@/services/HuaWeiSnCenter";
import moment from "moment";

import { formatMessage } from "umi-plugin-react/locale";
import Loading from "@/components/Loading";
import { join } from "lodash";

const {Option} = Select

class TaskAddForm extends React.Component {
  constructor(props) {
    super(props);
    const id= props.id

    this.state = {
      loading: false, // 用户详细信息的加载状态，用户页面loading效果
      submiting: false, // 表单提交状态
      detail: {}, // 
      task_info:{},
      startTime:moment(),
      endTime:moment(),
      id 
    };
  }

  async componentDidMount() {

    this.loadData(this.state.id);
  }


  // 加载用户信息
  loadData = async id => {
    this.setState({ loading: true });
    let projectList = await getAllProject()
    let userList = await getAllUser()

    loadTaskDetail(id)
      .then(async res => {
        // 加载项目列表
        let member = []
        if(res.member){
          let memberArr = res.member.split(',')
          memberArr.map((val)=> {
            member.push(Number(val))
          })
        }

        this.setState({
          detail:res,
          projectId:res.projectId ? res.projectId : 0,
          startTime:res.startTime ? res.startTime : null,
          endTime:res.endTime ? res.endTime : null,
          member: member,
          priority:res.priority ? res.priority : 1,
          status:res.status ? res.status : 1,
          projectList:projectList.data,
          userList:userList.data,
          
        });
        if(res.task_info){
          let managerList = await getManagerList()
          let wplList = await getWplList()
          let huaweiSnList = await getAllSnList()

          this.setState({
            task_info:res.task_info,
            manager:res.task_info.manager,
            wpl:res.task_info.wpl,
            sn:res.task_info.sn,
            department:res.task_info.department,
            showExpand:true,
            managerList:managerList.data,
            huaweiSnList:huaweiSnList.data,
            wplList:wplList.data
          })
        }
        
      })
      .finally(() => {
        this.setState({
          loading: false
        });
      });

  };

  handleSubmit = async e => {
    e.preventDefault();
    if (this.submiting) {
      return;
    }
    // setState为异步动作，直接设置submiting变量作为限制
    this.submiting = true;
    this.setState({
      submiting: true
    });
    this.props.form.validateFields(async (err, fieldsValue) => {
      if (err) {
        this.submiting = false;
        this.setState({
          submiting: false
        });
        return;
      }
      let task_info = this.state.task_info
      if(this.state.showExpand){
        task_info['language'] = fieldsValue.language
        task_info['number'] = fieldsValue.number
      }
      
      const params = {
        id: this.state.id,
        title:fieldsValue.title,
        projectId:this.state.projectId,
        startTime:this.state.startTime ? this.state.startTime : moment().format('YYYY-MM-DD'),
        endTIme:this.state.endTime ? this.state.endTime : moment().format('YYYY-MM-DD'),
        member:this.state.member.length > 0 ? join(this.state.member,',') : '',
        priority:this.state.priority,
        status:this.state.status,
        task_info:task_info,
        sort:fieldsValue.sort
      };

      console.log(params)

      addTask(params).then(res => {
        this.submiting = false;
        this.setState({
          submiting: false
        });
        if (res && res.status !== 200) {
        } else {
          notification.success({
            message: "添加成功"
          });
          this.props.handleAddCancel();
          this.props.refresh();
        }
      });
    });
  };

  onProjectChange = async (e) => {
    this.setState({projectId:e})
    // 获取本项目是否是华为项目
    let projectInfo = await loadProjectDetail(e)
    
    if(projectInfo.isHuaWei == 1){

      let managerList = await getManagerList()
      let wplList = await getWplList()
      let huaweiSnList = await getAllSnList()

      this.setState({
        showExpand:true,
        managerList:managerList.data,
        wplList:wplList.data,
        huaweiSnList:huaweiSnList.data
      })
    }else{
      this.setState({showExpand:false,task_info:{}})
    }
  }

  onStartChange = (e,dateString) => {
    this.setState({startTime:dateString})
  }

  onEndChange = (e,dateString) => {
    this.setState({endTime:dateString})
  }
  
  onMemberChange = (e) => {
    this.setState({member:e})
  }

  onStatusChange = e => {
    this.setState({status:e.target.value})
  }

  onPriorityChange = e => {
    this.setState({priority:e.target.value})
  }

  // task_info
  onManagerChange = e => {
    let task_info = this.state.task_info
    task_info['manager'] = e
    this.setState({task_info:task_info,manager:e})
  }

  onWplChange = e => {
    let task_info = this.state.task_info
    task_info['wpl'] = e
    this.setState({task_info:task_info,wpl:e})
  }

  onSnChange = e => {
    let task_info = this.state.task_info
    task_info['sn'] = e
    this.setState({task_info:task_info,sn:e})
  }

  onDepartmentChange = e => {
    let task_info = this.state.task_info
    task_info['department'] = e
    this.setState({task_info:task_info,department:e})
  }
  
  render() {
    const { getFieldDecorator } = this.props.form;
    const { submiting,projectList,userList,wplList,managerList,huaweiSnList } = this.state;

    const titleExtraButton = (
      <Row type="flex" gutter={12} align="middle">
        <Col>
          <Button
            type="primary"
            loading={submiting}
            onClick={this.handleSubmit}
          >
            提交
          </Button>
        </Col>
        <Col>
          <Button onClick={this.props.handleAddCancel}>返回</Button>
        </Col>
      </Row>
    );


    const { detail,task_info, loading} = this.state;

    const rowGutter = [16, 16];
  
    return (
      <Card>
        {loading ? (
          <Loading />
        ) : (
          <Form labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal">

            <Row type="flex" gutter={rowGutter}>
              <Col span={24}>
                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="任务名称">
                      {getFieldDecorator("title", {
                        initialValue: detail.title ? detail.title : '',
                        rules: [
                          {
                            required: true,
                            message: formatMessage({
                              id: "请输入任务名称"
                            })
                          }
                        ]
                      })(<Input style={{width: 400 }} />)}
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                  <Form.Item label="所属项目">
                    <Select defaultValue={this.state.projectId} style={{width: 400 }} onChange={this.onProjectChange} showSearch>
                      <Option value={0}>--请选择--</Option>
                      {
                        projectList && projectList.map((item)=> {
                          return <Option value={item.id}>{item.projectName}</Option>
                        })
                      }

                    </Select>
                  </Form.Item>
                  </Col>
                </Row>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="开始时间">
                      {getFieldDecorator("startTime", {
                        initialValue:this.state.startTime ? moment(this.state.startTime) :moment(),
                      })(<DatePicker onChange={this.onStartChange} format={'YYYY-MM-DD'}/>)}
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="计划完成时间">
                      {getFieldDecorator("endTime", {
                        initialValue:this.state.endTime ? moment(this.state.endTime) :moment(),
                      })(<DatePicker onChange={this.onEndChange} format={'YYYY-MM-DD'}/>)}
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="参与人员">
                    <Select
                      mode="multiple"
                      style={{ width:400 }}
                      // placeholder="Please select"
                      defaultValue={this.state.member}
                      onChange={this.onMemberChange}
                    >
                      <Option value={0}>--请选择--</Option>
                      {
                        userList && userList.map((item)=> {
                          return <Option value={item.id} key={item.id}>{item.userName}</Option>
                        })
                      }
                    </Select>
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="优先级">
                      <Radio.Group onChange={this.onPriorityChange} value={this.state.priority}>
                        <Radio value={1}>高</Radio>
                        <Radio value={2}>中</Radio>
                        <Radio value={3}>低</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="状态">
                      <Radio.Group onChange={this.onStatusChange} value={this.state.status}>
                        <Radio value={1}>进行中</Radio>
                        <Radio value={2}>已完成</Radio>
                        <Radio value={3}>已暂停</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                </Row>

                {
                  this.state.showExpand ?
                  (
                  <Row>
                    <Row gutter={rowGutter}>
                      <Col span={24}>
                        <Form.Item label="WPL" >
                          <Select defaultValue={this.state.wpl} style={{width: 400 }} onChange={this.onWplChange} showSearch>
                            <Option value={0}>--请选择--</Option>
                            {
                              wplList && wplList.map((item)=> {
                                return <Option value={item.id}>{item.name}</Option>
                              })
                            }

                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={rowGutter}>
                      <Col span={24}>
                        <Form.Item label="服务经理">
                          <Select defaultValue={this.state.manager} style={{width: 400 }} onChange={this.onManagerChange} showSearch>
                            <Option value={0}>--请选择--</Option>
                            {
                              managerList && managerList.map((item)=> {
                                return <Option value={item.id}>{item.name}</Option>
                              })
                            }

                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={rowGutter}>
                      <Col span={24}>
                        <Form.Item label="团队">
                          <Select defaultValue={this.state.department} style={{width: 400 }} onChange={this.onDepartmentChange} showSearch>
                            <Option value={0}>--请选择--</Option>
                            <Option value={1}>设计</Option>
                            <Option value={2}>技术</Option>
                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>

                    <Form.Item label="语种">
                      {getFieldDecorator("language", {
                        initialValue: task_info.language ? task_info.language : '',
                        rules: [
                          {
                            required: true,
                            message: formatMessage({
                              id: "请输入语种"
                            })
                          }
                        ]
                      })(<Input style={{width: 400 }} />)}
                    </Form.Item>

                    <Row gutter={rowGutter}>
                      <Col span={24}>
                        <Form.Item label="条目编号">
                          <Select defaultValue={this.state.sn} style={{width: 400 }} onChange={this.onSnChange} showSearch>
                            <Option value={0}>--请选择--</Option>
                            {
                              huaweiSnList && huaweiSnList.map((item)=> {
                                return <Option value={item.id}>{item.sn}</Option>
                              })
                            }

                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>

                    <Form.Item label="数量">
                      {getFieldDecorator("number", {
                        initialValue: task_info.number ? task_info.number : 1,
                        rules: [
                          {
                            required: true,
                            message: formatMessage({
                              id: "请输入数量"
                            })
                          }
                        ]
                      })(<Input style={{width: 400 }} />)}
                    </Form.Item>
                  </Row>
                  )
                  :null
                }

                <Row gutter={rowGutter}>
                  <Col span={24}>
                    <Form.Item label="排序" help="数值越大排序越靠前">
                      {getFieldDecorator("sort", {
                        initialValue: 0,
                      })(<Input style={{width: 200 }} />)}
                    </Form.Item>
                  </Col>
                </Row>

                
              </Col>
            </Row>
            

            <Row gutter={rowGutter}>
              <Col span={24} style={{marginLeft:'110px',marginTop:'20px'}}>
                {titleExtraButton}
              </Col>
            </Row>
          </Form>
        )}
      </Card>
    );
  }
}

const WrappedTaskAddForm = Form.create({ name: "Task_add" })(
  TaskAddForm
);
export default WrappedTaskAddForm;
